﻿//---------------------------------------------------------------------
// Author: Reinhard Lehrbaum
//
// Description: Lists all domain controller.
//
// Creation Date: 2006-12-20
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.DirectoryServices;
using System.Management.Automation;
using System.Text;

namespace Pscx.Commands.DirectoryServices
{
    [Cmdlet(VerbsCommon.Get, "DomainController"),
     Description("Gets a list of available domain controller in the current forest/domain.")]
    public class GetDomainControllerCommand : Pscx.Commands.Internal.PscxDirectoryServiceCommandBase
    {
        protected override void ProcessRecord()
        {
            DirectoryEntry RootDSE = GetDirectoryEntry("LDAP://" + (!string.IsNullOrEmpty(FServer) ? FServer + "/" : "") + "RootDSE");
            DirectoryEntry ConfigContainer = GetDirectoryEntry("LDAP://" + (!string.IsNullOrEmpty(FServer) ? FServer + "/" : "") + RootDSE.Properties["configurationNamingContext"].Value);

            DirectorySearcher ConfigSearcher = new DirectorySearcher(ConfigContainer);
            //get the Directory Service Agents
            ConfigSearcher.Filter = "(&(objectClass=nTDSDSA))";

            foreach (SearchResult result in ConfigSearcher.FindAll())
            {
                DirectoryEntry dsa = GetDirectoryEntry(result.Path);
                DirectoryEntry server = dsa.Parent;
                DirectoryEntry site = server.Parent.Parent;

                WriteObject(new DCServerInfo(
                    server.Properties["cn"].Value.ToString(),  //Servername
                    server.Properties["dNSHostName"].Value.ToString(),  //FQDN (Fully Qualified Domain Name)
                    server.Properties["serverReference"].Value.ToString(), //Distinguished Name
                    site.Properties["cn"].Value.ToString(), //Sitename
                    dsa.Properties["options"].Value != null ? ((int)dsa.Properties["options"].Value) == 1 : false)); //Global Catalog
            }
        }
    }
}
